package com.xydtech.busiflw.controller;

import com.xydtech.busiflw.domain.BusiflDocList;
import com.xydtech.busiflw.domain.BusiflDocReg;
import com.xydtech.busiflw.service.IBusiflDocListService;
import com.xydtech.busiflw.service.IBusiflDocRegService;
import com.xydtech.common.annotation.Log;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.page.TableDataInfo;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.file.FileUploadUtils;
import com.xydtech.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.util.UriEncoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 业务流程影像上传登记Controller
 *
 * @author JHON
 * @date 2022-01-05
 */
@Controller
@RequestMapping("/busiflw/docReg")
public class BusiflDocRegController extends BaseController {
    private String prefix = "busiflw/docReg";

    @Autowired
    private IBusiflDocRegService busiflDocRegService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IBusiflDocListService busiflDocListService;
    //文件分布式存储开关
    @Value("${busiplat.minioUpload}")
    private boolean minioUpload;


    @GetMapping("/{versionId}/{instanceId}/{stepId}")
    public String docReg(@PathVariable("versionId") Long versionId, @PathVariable("instanceId") String instanceId, @PathVariable("stepId") Long stepId, ModelMap mmap) {
        mmap.put("versionId", versionId);
        mmap.put("instanceId", instanceId);
        mmap.put("stepId", stepId);
        return prefix + "/docReg";
    }

    @GetMapping("hisDocReg/{versionId}/{instanceId}/{stepId}")
    public String hisDocReg(@PathVariable("versionId") Long versionId, @PathVariable("instanceId") String instanceId, @PathVariable("stepId") Long stepId, ModelMap mmap) {
        mmap.put("versionId", versionId);
        mmap.put("instanceId", instanceId);
        mmap.put("stepId", stepId);
        return prefix + "/hisDocReg";
    }

    /**
     * 查询业务流程影像上传登记列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BusiflDocReg busiflDocReg) {
        startPage();
        List<BusiflDocReg> list = busiflDocRegService.selectBusiflDocRegList(busiflDocReg);
        return getDataTable(list);
    }

    /**
     * 删除业务流程影像上传登记
     */
    @Log(title = "删除业务流程影像上传登记", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(busiflDocRegService.deleteBusiflDocRegByDocRegIds(ids));
    }

    /**
     * 跳转上传页面
     * @Title: docReg
     * @param docRegId
     * @param instanceId
     * @param docCode
     * @param mmap
     * @return java.lang.String
     * @exception
     * @author JHON
     * @Date 2022/1/6 9:10
     **/
    @GetMapping("/upload/{docRegId}/{instanceId}/{docCode}")
    public String docReg(@PathVariable("docRegId") Long docRegId, @PathVariable("instanceId") String instanceId, @PathVariable("docCode") String docCode, ModelMap mmap) {
        mmap.put("docRegId", docRegId);
        mmap.put("instanceId", instanceId);
        mmap.put("docCode", docCode);
        return prefix + "/upload";
    }

    /**
     * 流程多文件上传请求
     */
    @Log(title = "流程多文件上传请求", businessType = BusinessType.UPDATE)
    @PostMapping("/uploads/{docRegId}/{instanceId}/{docCode}")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files, @PathVariable("docRegId") Long docRegId, @PathVariable("instanceId") String instanceId, @PathVariable("docCode") String docCode) throws Exception {
        try {
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
            if (sysDept != null) {
                deptId = sysDept.getDeptId();
            }
            // 上传文件路径
            String filePath = XydtechBusiPlatConfig.getProfile() + "/" + deptId + "/busifl/" + instanceId + "/" + docCode;
            for (MultipartFile file : files) {
                int index = file.getOriginalFilename().lastIndexOf(".");
                String fileName = file.getOriginalFilename().substring(0, index);
                //文件类型
                String fileType = file.getOriginalFilename().substring(index + 1);
                // 上传并返回新文件名称
                String fileUrl = FileUploadUtils.upload(filePath, file, minioUpload);
                BusiflDocList busiflDocList = new BusiflDocList();
                busiflDocList.setDocRegId(docRegId);
                busiflDocList.setUserId(ShiroUtils.getSysUser().getUserId());
                busiflDocList.setFileName(fileName);
                busiflDocList.setFileType(fileType);
                busiflDocList.setFileUrl(fileUrl);
                busiflDocListService.insertBusiflDocList(busiflDocList);
            }
            AjaxResult ajax = AjaxResult.success();
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 跳转预览页面
     * @Title: docReg
     * @param docRegId
     * @param mmap
     * @return java.lang.String
     * @exception
     * @author JHON
     * @Date 2022/1/6 9:10
     **/
    @GetMapping("/preview/{docRegId}")
    public String preview(@PathVariable("docRegId") Long docRegId, ModelMap mmap) {
        BusiflDocList busiflDocList = new BusiflDocList();
        busiflDocList.setDocRegId(docRegId);
        List<BusiflDocList> list = busiflDocListService.selectBusiflDocListList(busiflDocList);
        mmap.put("docList", list);
        return prefix + "/preview";
    }

    /**
     * 跳转预览页面
     * @Title: docReg
     * @param instanceId
     * @param mmap
     * @return java.lang.String
     * @exception
     * @author JHON
     * @Date 2022/1/6 9:10
     **/
    @GetMapping("/previewAll/{instanceId}")
    public String previewAll(@PathVariable("instanceId") String instanceId, ModelMap mmap) {
        List<BusiflDocList> list = busiflDocListService.selectBusiflDocListByInstanceId(instanceId);
        mmap.put("docList", list);
        return prefix + "/preview";
    }

    /**
     *重载影像资料上传列表
     * @Title: reload
     * @param versionId
     * @param instanceId
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author JHON
     * @Date 2022/1/6 13:21
     **/
    @Log(title = "重载影像资料上传列表", businessType = BusinessType.INSERT)
    @PostMapping("/reload")
    @ResponseBody
    public AjaxResult reload(Long versionId, String instanceId) {
        /**初始化资料上传登记表*/
        BusiflDocReg busiflDocReg = new BusiflDocReg();
        busiflDocReg.setInstanceId(instanceId);
        busiflDocReg.setVersionId(versionId);
        int row = busiflDocRegService.insertBusiflDocReg(busiflDocReg);
        return success("载入" + row + "条数据！");
    }

    @GetMapping("/download")
    public void getFile(String fileUrl, String fileName, String fileType, HttpServletResponse response) throws IOException {
        String[] filePaths = fileUrl.split("profile");
        Path path = Paths.get(XydtechBusiPlatConfig.getProfile() + filePaths[1]);
        byte[] bytes = new byte[0];
        try {
            fileName = fileName + "\\." + fileType;
            bytes = Files.readAllBytes(path);
            response.setHeader("Content-Disposition", "attachment;filename="
                    + UriEncoder.encode(fileName));
            response.getOutputStream().write(bytes);
        } finally {
            response.getOutputStream().close();
        }
    }
}
